package user;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
//    //查找全部员工信息
//    public User1 AllE(Connection con, User1 user1) throws SQLException {
//        User1 rseultUser = null;
//        String sql = "select * from user where username = ? AND password = ? AND role = ?";
//        PreparedStatement patmt = (PreparedStatement) con.prepareStatement(sql);
//            patmt.setString(1,user1.getUsername());
//            patmt.setString(2, user1.getPassword());
//            patmt.setInt(3,user1.getRole());
//            ResultSet rs = patmt.executeQuery();
//            if (rs.next()){
//                rseultUser = new User1();
//                rseultUser.setId(rs.getInt("id"));
//                rseultUser.setUsername(rs.getString("name"));
////                rseultUser.setSex(rs.getString("sex"));
//            }
//        return rseultUser;
//    }

    //注册新用户
    public void register(User user) throws SQLException{
        String sql = "insert into user(username,sex,password,role) values (?,?,?,?)";
        try(Connection conn = DBUtil.getConn()) {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getSex());
            pstmt.setString(3,user.getPassword());
            pstmt.setInt(4,user.getRole());
            pstmt.executeUpdate();

        }
    }

    //登录验证
    public User login(String username,String password)throws SQLException{
        String sql = "select userId,username,sex,role from user where username = ? and password = ?";
        try (Connection conn = DBUtil.getConn()){
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            ResultSet rs = pstmt.executeQuery();
            if(rs.next()){
                User user = new User();
                user.setUserId(rs.getInt("userId"));
                user.setUsername(rs.getString("username"));
                user.setSex(rs.getString("sex"));
                user.setRole(rs.getInt("role"));
                return user;
            }
            return null;     //登录失败
        }
    }
}
